﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NetworkManager : MonoBehaviour
{
    static NetworkManager _instance;
    public static NetworkManager Instance
    {
        get
        {
            return _instance;
        }
    }

    SocketClient client;
    Queue<ByteBuffer> events = new Queue<ByteBuffer>();
    HanderCenter center = new HanderCenter();
    void Awake()
    {
        if (_instance == null)
        {
            _instance = this;
            Init();
        }
        else
            Destroy(gameObject);
    }
    void Init()
    {
        DontDestroyOnLoad(gameObject);
        client = new SocketClient();
    }
    //消息子线程和主线程同步数据
    public void AddEvent(ByteBuffer buffer)
    {
        events.Enqueue(buffer);
    }
    // Update is called once per frame
    void Update()
    {
        if (events.Count > 0)
        {           
            center.ReceiveMessage(events.Dequeue());
        }
    }
    public void Send(Protocal type, string msg)
    {
        client.Send((byte)type, msg);
    }
    public void Send(Protocal type, byte[] buffer)
    {
        client.Send((byte)type, buffer);
    }
    public void Send<T>(Protocal type, T t)where T:ProtoBuf.IExtensible
    {
        client.Send((byte)type, ProtoHelper.Serialize<T>(t));
    }
}
